package com.sudo.boot.service.sys.jobservice;

import com.sudo.boot.base.constant.TimeFormatConstant;
import com.sudo.boot.base.constant.enums.EnumStatus;
import com.sudo.boot.base.pojo.JsonRes;
import com.sudo.boot.base.util.LocalDateTimeUtil;
import com.sudo.boot.common.constant.enums.SysJobAction;
import com.sudo.boot.common.constant.enums.SysJobResult;
import com.sudo.boot.email.pojo.MailInfo;
import com.sudo.boot.email.service.ISendMsgHandle;
import com.sudo.boot.mapper.sys.entity.SysJobLog;
import com.sudo.boot.mapper.sys.mapper.SysJobLogMapper;
import com.sudo.boot.service.sys.jobservice.mail.MailInfoUtil;
import com.sudo.boot.threadpool.annotation.AsyncTask;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @Author：DayDayUp
 * @Create：2023/2/11 15:13
 */
@Slf4j
@Service
public class LogAndEmailServiceImpl implements LogAndEmailService {
    @Resource
    private SysJobLogMapper sysJobLogMapper;
    @Resource
    private ISendMsgHandle iSendMsgHandle;
    @Resource
    private AsyncTaskExecutor asyncTaskExecutor;

    @AsyncTask
    @Override
    public void asyncLocalJobLogAndEmail(Map<String, Object> tlMap, JsonRes<?> jsonRes, SysJobAction sysJobAction) {
        this.setJobLogAndEmail(tlMap, jsonRes.getCode(), jsonRes.getMsg(), jsonRes.getData(), sysJobAction);
    }

    private void setJobLogAndEmail(Map<String, Object> tlMap, Integer status, String msg, Object data, SysJobAction sysJobAction){

        Integer jobId = Integer.parseInt(tlMap.get("tl_jobId").toString());
        Object tlJobServer = tlMap.get("tl_jobServer");
        String jobServer = null;
        if (tlJobServer != null){
            jobServer = tlJobServer.toString();
        }
        String jobBean = tlMap.get("tl_jobBean").toString();
        String jobMethod = tlMap.get("tl_jobMethod").toString();
        Object tlJobParams = tlMap.get("tl_jobParams");
        String jobParams = null;
        if (tlJobParams != null){
            jobParams = tlJobParams.toString();
        }
        String logStatus = tlMap.get("tl_logStatus").toString();
        String mailStatus = tlMap.get("tl_mailStatus").toString();
        String jobResult = status == 200 ? SysJobResult.SUCCESS.getCode() : SysJobResult.FAIL.getCode();
        LocalDateTime jobStartTime = (LocalDateTime)tlMap.get("tl_jobStartTime");
        LocalDateTime jobEndTime = LocalDateTime.now();
        String jobStartTimeStr = LocalDateTimeUtil.dateTime2Str(jobStartTime, TimeFormatConstant.dateTimes4);
        String jobEndTimeStr = LocalDateTimeUtil.dateTime2Str(jobEndTime,TimeFormatConstant.dateTimes4);

        SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobId(jobId);
        sysJobLog.setJobServer(jobServer);
        sysJobLog.setJobBean(jobBean);
        sysJobLog.setJobMethod(jobMethod);
        sysJobLog.setJobParams(jobParams);
        sysJobLog.setJobResult(jobResult);
        sysJobLog.setJobNote(msg);
        if (data == null) {
            data = "";
        }
        sysJobLog.setJobNoteDesc(data.toString());
        sysJobLog.setJobStartTime(jobStartTimeStr);
        sysJobLog.setJobEndTime(jobEndTimeStr);
        Duration between = Duration.between(jobStartTime, jobEndTime);
        long useTime = between.toMillis();
        sysJobLog.setJobUseTime(useTime);
        sysJobLog.setJobAction(sysJobAction.getCode());

        // 是否记录日志
        asyncTaskExecutor.execute(()->{
            if (EnumStatus.ON.getCode().equals(logStatus)){
                // 日志写入Mysql
                sysJobLogMapper.insertSelective(sysJobLog);
            }
        });

        // 是否发邮件提醒
        asyncTaskExecutor.execute(() -> {
            // 执行失败则发送邮件提醒
            if (SysJobResult.FAIL.getCode().equals(jobResult)) {
                Object mailAddressObject = tlMap.get("tl_mailAddress");
                if (mailAddressObject != null) {
                    String mailAddress = mailAddressObject.toString();
                    if (StringUtils.hasText(mailAddress) && EnumStatus.ON.getCode().equals(mailStatus)) {
                        MailInfo mailInfo = MailInfoUtil.methodJobExceptionMail(mailAddress, sysJobLog);
                        iSendMsgHandle.sendHtmlEmail(mailInfo,true);
                    }
                }
                }
        });
    }

}
